import VuiComboBox from '../combo-box';
import SelectionItem from './option-item';
import './style.css';

export default class VuiMultipleSelector extends VuiComboBox {
  constructor(config, action) {
    if (!config.min) {
      config.min = 0;
    }
    super(config);

    const className = {
      container: 'vui-multiple-selector',
      content: 'vui-selector-content',
      title: 'vui-selector-title',
      text: 'vui-selector-text'
    };

    this._className = Object.assign(this._className, className);
    this.values = config.defaultValue || [];
    this.action = action;
  }

  init() {
    const config = this._config;
    const defaultValue = config.defaultValue || [];
    config.defaultValue = defaultValue.length ? '' : '请选择...';
    this.options = config.options;
    config.options = [];
    this.initUI();
    return this;
  }

  initUI() {
    super.initUI();
    this.dropdown.removeProperty('left');
    this.dropdown.removeProperty('top');
    this.setOption();
  }

  setOption() {
    const options = this.options;
    const dp = this.dropdown;
    const config = this._config;
    dp.clean();
    for (let i = 0; i < options.length; i++) {
      const option = options[i];
      const item = new SelectionItem(option, index => {
        if (this.values.length > config.min) {
          this.removeValue(index);
          this.action(this.values);
          return true;
        }
      }).init();
      item.setClickListener(evt => {
        if (item.selected) {
          if (this.values.length > config.min) {
            this.removeValue(item.option.value);
            item.removeSelected();
          }
        } else {
          const value = item.option.value;
          this.setValue(value);
          item.setSelected();
          this.text.append(item.textItem);
        }
        evt.stopPropagation();
        this.action(this.values);
      });
      const defaultIndex = this.values.indexOf(option.value);
      if (defaultIndex !== -1) {
        item.setSelected();
        this.text.append(item.textItem);
      }
      dp.append(item);
    }
  }

  setValue(value) {
    const values = this.values;
    const text = this.text;
    const index = values.push(value);
    if (index === 1) {
      text.clean();
    }
  }

  removeValue(value) {
    const config = this._config;
    this.values = this.values.filter(v => v !== value);
    if (!this.values.length) {
      this.text.setInnerText(config.defaultValue);
    }
  }
}
